package com.hisense.proxy.busitrans.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hisense.proxy.busitrans.vo.HxFdcprBusitransApplyInvoiceHeadVO;
import com.hisense.proxy.busitrans.vo.RedInvoiceReqProxyVO;
import com.hisense.proxy.service.entity.output_invoice.InvoiceBuildParam;
import com.hisense.proxy.service.utils.HttpClientUtil;
import com.hisense.proxy.service.utils.URLConfigEnum;

@RestController
@RequestMapping("apply")
public class HxFdcprBusitransApplyInvoiceProxyController {

    private static Logger log = LoggerFactory.getLogger(HxFdcprBusitransApplyInvoiceProxyController.class);

	
	@Autowired
	private InvoiceBuildParam invoiceParam;

	@PostMapping("/blue")
	public JSONObject applyBlueInvoice(@RequestParam(required = false, defaultValue = "false") Boolean isApply, @RequestBody HxFdcprBusitransApplyInvoiceHeadVO bodyData) throws Exception {
		MergeInvoiceDetailUtil.mergeBodyDetail(bodyData);
		Map<String, String> paramsMap = invoiceParam.buildInsertWithArrayPostParam(bodyData, isApply);

		log.info("applyBlueInvoice: {}", paramsMap);
		String result = HttpClientUtil.post(URLConfigEnum.INSERT_WITH_ARRAY_URL.getUrl(), (Map) paramsMap);
		JSONObject resultObj = JSON.parseObject(result);

		return resultObj;
	}

	@PostMapping("/blueSplit")
	public JSONObject applySplitBlueInvoice(@RequestParam(required = false, defaultValue = "false") Boolean isApply, @RequestBody HxFdcprBusitransApplyInvoiceHeadVO bodyData) throws Exception {
		MergeInvoiceDetailUtil.mergeBodyDetail(bodyData);
		Map<String, Object> paramsMap = invoiceParam.insertWithSplit(bodyData, isApply);

		log.info("applySplitBlueInvoice: {}", paramsMap);
		String result = HttpClientUtil.post(URLConfigEnum.INSERT_WITH_SPLIT.getUrl(), (Map) paramsMap);
		JSONObject resultObj = JSON.parseObject(result);

		return resultObj;
	}

	@PostMapping("/red")
	public JSONObject redInvoice(@RequestParam(required = false, defaultValue = "false") Boolean isApply, @RequestParam String orgcode, @RequestBody List<RedInvoiceReqProxyVO> reqVos) throws Exception {
		log.info("Requesting red invoice body org code & params : {} - {}", orgcode, JSON.toJSONString(reqVos));
		
		JSONObject result = new JSONObject();
		List<RedInvoiceReqProxyVO> success = new ArrayList<RedInvoiceReqProxyVO>();
		List<RedInvoiceReqProxyVO> fail = new ArrayList<RedInvoiceReqProxyVO>();

		// 将发票 按照专票/其他类型进行分组
//		List<RedInvoiceReqProxyVO> zhuanpiaos = reqVos.stream().filter(e -> "4".equals(e.getInvoiceType()))
//				.collect(Collectors.toList());
//		List<RedInvoiceReqProxyVO> pupiaos = reqVos.stream().filter(e -> !"4".equals(e.getInvoiceType()))
//				.collect(Collectors.toList());

		List<RedInvoiceReqProxyVO> pupiaos = reqVos;
		if (pupiaos.size() > 0) {
			Map<String, Object> paramsMap = invoiceParam.red(orgcode, pupiaos, isApply);
			String postResult = HttpClientUtil.post(URLConfigEnum.RED.getUrl(), (Map<String, Object>) paramsMap);
			JSONObject parseObject = JSON.parseObject(postResult);

			pupiaos.forEach(pupiao -> {
				if ("0000".equals(parseObject.get("code"))) {
					success.add(pupiao);
				} else {
					pupiao.setFailReason(parseObject.getString("msg"));
					fail.add(pupiao);
				}

			});
		}

//		if (zhuanpiaos.size() > 0) {
//			for (RedInvoiceReqProxyVO zhuanpiao : zhuanpiaos) {
//				Map<String, Object> paramsMap = new HashMap<String, Object>();
//				paramsMap.put("yfpDm", zhuanpiao.getFpdm());
//				paramsMap.put("yfpHm", zhuanpiao.getFphm());
//				String postResult = HttpClientUtil.post(URLConfigEnum.SPECIALRED.getUrl(), paramsMap);
//				JSONObject parseObject = JSON.parseObject(postResult);
//				if ("0000".equals(parseObject.get("code"))) {
//					success.add(zhuanpiao);
//				} else {
//					zhuanpiao.setFailReason(parseObject.getString("msg"));
//					fail.add(zhuanpiao);
//				}
//			}
//		}
		
		result.put("code","0000");
		result.put("success", success);;
		result.put("fail", fail);

		return result;
	}
	
	
	@PostMapping("/invalid")
	public JSONObject invalidInvoice(@RequestParam(required = false, defaultValue = "false") Boolean isApply, @RequestBody List<RedInvoiceReqProxyVO> reqVos) throws Exception {
		log.info("Requesting invalid invoice body org code & params : {}", JSON.toJSONString(reqVos));

		JSONObject result = new JSONObject();
		List<RedInvoiceReqProxyVO> success = new ArrayList<RedInvoiceReqProxyVO>();
		List<RedInvoiceReqProxyVO> fail = new ArrayList<RedInvoiceReqProxyVO>();
		
		if (reqVos.size() > 0) {
			reqVos.forEach(reqVo -> {
				Map<String, Object> paramMap = InvoiceBuildParam.buildInvalidParam(reqVo.getFphm(), reqVo.getFpdm());
		        String postResult = null;
				try {
					postResult = HttpClientUtil.post(URLConfigEnum.INVALID.getUrl(), paramMap);
				} catch (Exception e) {
					reqVo.setFailReason(e.getMessage());
					fail.add(reqVo);
					return;
				}
				JSONObject parseObject = JSON.parseObject(postResult);
				
				if ("0000".equals(parseObject.get("code"))) {
					success.add(reqVo);
				} else {
					reqVo.setFailReason(parseObject.getString("msg"));
					fail.add(reqVo);
				}

			});
		}

		result.put("code","0000");
		result.put("success", success);;
		result.put("fail", fail);

		return result;
	}
}
